/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
 var web_url="http://192.168.1.108:8080/ThunderShop/";
  var resource_url="http://192.168.1.108:8080/";
(function($, owner) {
	/**
	 * 用户登录
	 **/
   

	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if(loginInfo.account.length < 1) {
			return callback('账号最短为 1 个字符');
		}
		if(loginInfo.password.length < 1) {
			return callback('密码最短为 1个字符');
		}

		//http://58.59.25.14:40014
		//http://192.168.43.230:623
		mui.ajax('http://60.217.194.66:630/api/auth/login', {
			data: {
				user_name: loginInfo.account,
				password: loginInfo.password
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 8000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json'
			},
			success: function(data) {
				console.log(data);
				//服务器返回响应，根据响应结果，分析是否登录成功；
				if(data.status == 200) {
					return owner.setUserToken(data.result.token, callback);
					//return owner.createState(loginInfo.account, callback);
				} else {
					//console.log(owner.getUserToken());
					return callback(data.message);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				return callback('登录错误');
			}
		});

	};

	owner.createState = function(name, callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		owner.setState(state);
		return callback();
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if(regInfo.account.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if(regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if(!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		users.push(regInfo);
		localStorage.setItem('$users', JSON.stringify(users));
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}
	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}

	/******************************
	 * 从这里开始，都是我自己写的方法  *
	 * 每一个都要加注释，以便阅读修改  * 
	 * ****************************/

	/**
	 * 获取本地存储的用户token
	 **/
	owner.getUserToken = function() {
		var token = localStorage.getItem('$user_token') || "{}";
		return JSON.parse(token);
	};

	/**
	 * 设置本地存储的用户token
	 **/
	owner.setUserToken = function(token) {
		token = token || {};
		localStorage.setItem('$user_token', JSON.stringify(token));
	};
	/**
	 * 清除本地存储的用户token
	 **/
	owner.removeUserToken = function() {
		console.log("清除token之前：" + localStorage.getItem('$user_token'));
		localStorage.removeItem('$user_token');
		localStorage.clear();
		console.log("清除token之后:" + localStorage.getItem('$user_token'));
	};

	owner.postServer = function(postData, result, callback) {
		callback = callback || $.noop;
		result = result || $.noop;
		postData = postData || {};
		var apiUrl = postData.apiUrl || 'http://192.168.31.201:8080/ThunderShop/"';
		var datas = postData.datas || {};
	   
		mui.ajax(apiUrl, {
			data: datas,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 5000, //超时时间设置为10秒；
			success: function(data) {
				//服务器返回响应，根据响应结果，分析是否登录成功；
			
				if(data.statusCode == 200) {
				
					return result(data);
				} else {
				
					return callback(data.msg);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log("请求失败地址："+apiUrl+errorThrown);
				return callback('请求错误');
			}
		});

	};
	
	/**
	 * 获取本地存储的厂区
	 **/
	owner.getFactory = function() {
		var token = localStorage.getItem('$factory') || "{}";
		return JSON.parse(token);
	};

	/**
	 * 设置本地存储的厂区
	 **/
	owner.setFactory = function(token) {
		token = token || {};
		localStorage.setItem('$factory', JSON.stringify(token));
	};
	/**
	 * 清除本地存储的厂区
	 **/
	owner.removeFactory = function() {
		console.log("清除factory之前：" + localStorage.getItem('$factory'));
		localStorage.removeItem('$factory');
		localStorage.clear();
		console.log("清除factory之后:" + localStorage.getItem('$factory'));
	};

}(mui, window.app = {}));